package cn.wx.scholar.neo4j.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import cn.wx.common.persistence.exception.MyException;
import cn.wx.common.persistence.web.ResponseCode;
import cn.wx.scholar.core.entity.News;
import cn.wx.scholar.core.entity.qo.NewsQ;
import cn.wx.scholar.core.service.NewsService;
import cn.wx.scholar.neo4j.entity.Neo4jNews;
import cn.wx.scholar.neo4j.entity.qo.Neo4jNewsQ;
import cn.wx.scholar.neo4j.repository.NewsRepository;
import cn.wx.scholar.tool.neo4j.Neo4jQueryTools;

@Service
public class Neo4jNewsService {
	
	@Autowired
    private NewsRepository newsRepository;
	
	@Autowired
	private NewsService newsService;
	
	/**
	 * 查看新闻详情功能
	 * @return
	 */
	public Neo4jNews findOneNews(Long id) {
		Optional<Neo4jNews> nws = newsRepository.findById(id);
		Neo4jNews nw = nws.get();
		if(nw != null) {
			NewsQ nQ = new NewsQ();
			nQ.setfId(nw.getfId());
			News cNews = newsService.queryUnique(nQ, News.class);
			
			if(cNews != null) {
				nw.setTextSrc_(cNews.getTextSrc_());
			}
		}
		return nw;
	}
	
	
	public Page<Neo4jNews> findAllNewsById(Neo4jNewsQ neo4jNewsQ){
		
		/**
		 * 参数判断
		 */
		if(neo4jNewsQ == null || 
				neo4jNewsQ.getExpertId()==null || 
				StringUtils.isBlank(neo4jNewsQ.getExpertName())) {
			
			throw new MyException(ResponseCode.PARAMETER_REQUIRED);
		}
		
		/**
		 * 查询知识图谱
		 */
		Page<Neo4jNews> pages = newsRepository.findAllNewsById(
				neo4jNewsQ.getExpertId(), 
				Neo4jQueryTools.basicLike(neo4jNewsQ.getExpertName()),
				PageRequest.of(neo4jNewsQ.getPageSkip(), neo4jNewsQ.getPageSize()));
		
		if(pages!=null && pages.getContent()!=null) {
			
			List<Long> nids = new ArrayList<>();
			for(Neo4jNews ew : pages.getContent()) {
				nids.add(ew.getfId());
			}
			if(nids != null && nids.size() > 0 ) {
				
				NewsQ nQ = new NewsQ();
				nQ.setfIds(nids);
				List<News> cNews = newsService.queryList(nQ);
				
				Map<Long,String> cNewsMap = null;
				
				if(cNews != null && cNews.size() > 0) {
					cNewsMap = new HashMap<>();
					for(News n : cNews) {
						cNewsMap.put(n.getfId(), n.getTextSrc_());
					}
				}
				
				if(cNewsMap != null) {
					for(Neo4jNews ew_ : pages.getContent()) {
						ew_.setTextSrc(cNewsMap.get(ew_.getfId()));
					}
				}
			}
	
		}
		return pages;
    }
}
